<?php

namespace app\service\system;

use app\model\system\SystemAreaModel;
use think\facade\Log;

/**
 * 区域服务
 */
class AreaService
{
    protected $model;

    public function __construct()
    {
        $this->model = new SystemAreaModel();
    }

    /**
     * 通过名称和级别查找地域ID
     * @param $name
     * @param $level
     * @param int $pid
     * @return int
     */
    public function getIdByName($name, $level, int $pid = 0): int
    {
        $query = $this->model
            ->where('level', $level)
            ->whereLike('name', "%$name%");
        if ($pid > 0) {
            $query->where('pid', $pid);
        }
        $id = $query->value('id');
        return empty($id) ? 0 : (int)$id;
    }

    /**
     * 通过ID获取Name
     * @param numeric $id
     * @return mixed|string
     */
    public function getNameById($id)
    {
        static $list = [];
        if (!empty($list[$id])) {
            $name = $list[$id];
        } else {
            $name = $this->model->where('id', $id)->value('name');
            //Log::info($name);
            $name = !empty($name) ? $name : "-";
            $list[$id] = $name;
        }
        return $name;
    }


}